/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
#define BPF_NO_GLOBAL_DATA
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
char LICENSE[] SEC("license") = "Dual BSD/GPL";
typedef int pid_t;

struct save_data {
    __u64 ns;
    int count;
};

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, int);
	__type(value, struct save_data);
} my_data_map SEC(".maps");

SEC("tracepoint/spi/spi_message_done")
int handle_tp(void *ctx){
	pid_t pid = bpf_get_current_pid_tgid() >> 32;
    __u64 ns = bpf_ktime_get_ns();
    __u64 diff_ns = 0;
    int index = 0;
    struct save_data value = {};
	struct save_data *p = bpf_map_lookup_elem(&my_data_map, &index);

    if (!p)
        return 1;

	value.count = p->count;
	if(value.count <= 0)
		value.count = 0;
	value.count ++;
    diff_ns = (ns - p->ns) / 1000;
    if (diff_ns >= 20 * 1000)
	    bpf_printk("BPF triggered from count:%d diff_ns: %llu us , last_ns: %llu\n", value.count, diff_ns, p->ns);
    value.ns = ns;

    bpf_map_update_elem(&my_data_map, &index, &value, BPF_ANY);
    return 0;
}